export const orderMealMixin = {
  data() {
    return {
      cartSelectData: [],
      cartTotalPrice: "0",
      cartChoosedNum: "0",
      pollTime: 3000,
      intervalPoll: null,
      clearIntervalPoll: false,
      startManId: "",
      orderMealMdName: "",
      storeFlagId: uni.getStorageSync("flag_id") || "",
      storeTableNum: uni.getStorageSync("food_table_num") || "",
      storageMdId: "-1",
    };
  },
  computed: {
    user_id() {
      let userInfo = uni.getStorageSync("userInfo");
      if (userInfo?.id) {
        return userInfo.id;
      } else {
        return "";
      }
    },
    userInfo() {
      let userInfo = uni.getStorageSync("userInfo");
      if (userInfo) return userInfo;
      return {};
    },
    storeMdData() {
      return uni.getStorageSync("storeMdData") || "";
    },
  },
  filters: {},
  methods: {
    /**
     * 加购物车
     * 先判断当前flag_id是否还生效
     * */
    async addGoodsToCart(data, cb) {
      let params = Object.assign({}, data);
      uni.showLoading({
        title: "加载中...",
        icon: "none",
      });
      if (this.storeFlagId) {
        params["flag_id"] = this.storeFlagId || "";
      }
      if (this.storeTableNum) {
        params["table_num"] = this.storeTableNum || "";
      }
      let mdData = uni.getStorageSync("storeMdData");
      let statusParams = { flag_id: params.flag_id };
      if (!mdData) {
        params["md_id"] = -1;
        statusParams["md_id"] = -1;
      }
      if (params.flag_id) {
        let status = await this.$allrequest.alipay.spellOrderStatus(
          statusParams
        );
        if (!status.code) {
          if (status.data.status == 1) {
            uni.removeStorageSync("flag_id");
            this.storeFlagId = "";
            uni.showToast({
              title: "该订单已结束，请重新下单！",
              duration: 2000,
              icon: "none",
            });
            clearInterval(this.intervalPoll);
            return;
          }
        }
      }

      this.$allrequest.alipay.orderMealToCart(params).then((res) => {
        if (!res.code) {
          if (this.storeFlagId != res.data.flag_id && res.data.flag_id) {
            this.setFlagIdToStorage(res.data.flag_id);
            this.storeFlagId = res.data.flag_id;
          }
          cb && cb();
          uni.hideLoading();
        }
      });
    },
    // 轮询购物车数据
    pollingCartData(cb) {
      if (!this.storeFlagId && !this.storeTableNum) {
        this.cartSelectData = [];
        this.cartChoosedNum = "0";
        this.cartTotalPrice = "0";
        return;
      }
      let params = {
        flag_id: this.storeFlagId,
        table_num: this.storeTableNum,
      };
      let mdData = uni.getStorageSync("storeMdData");
      if (!mdData) {
        params["md_id"] = -1;
      }
      this.$allrequest.alipay.pollingCartData(params).then((res) => {
        if (!res.code) {
          this.cartSelectData = res.data.list;
          this.cartTotalPrice = res.data.total_price.toFixed(2);
          this.startManId = res.data.user_id;
          this.orderMealMdName = res.data.md_name;
          this.cartChoosedNum = res.data.num || "0";
          cb && cb(res.data);
        }
      });
    },
    // 轮询购物车数据
    intervalPollingCartData() {
      this.intervalPoll = setInterval(() => {
        if (this.clearIntervalPoll) {
          clearInterval(this.intervalPoll);
          return;
        }
        this.pollingCartData();
      }, this.pollTime);
    },
    // 减一个
    reduceOneCartNum(data, cb) {
      this.$allrequest.alipay.reduceCartNum(data).then((res) => {
        if (!res.code) {
          cb && cb(res.data);
        }
      });
    },
    // 设置flag_id
    setFlagIdToStorage(data) {
      uni.setStorageSync("flag_id", data);
    },
    // 设置food_table_num
    setTableNumToStorage(data) {
      uni.setStorageSync("food_table_num", data);
    },
    // 清空购物车
    emptyCart(cb) {
      let params = {
        flag_id: this.storeFlagId,
        table_num: uni.getStorageSync("food_table_num"),
      };
      let mdData = uni.getStorageSync("storeMdData");
      if (!mdData) {
        params["md_id"] = -1;
      }
      this.$allrequest.alipay.clearAllCartData(params).then((res) => {
        if (!res.code) {
          uni.showToast({
            title: "清除成功！",
            duration: 2000,
            icon: "none",
          });
          cb && cb();
        }
      });
    },
    // 清空用户所选商品
    emptyUserCart(user_id, cb) {
      let params = {
        user_id,
        flag_id: this.storeFlagId,
      };
      let mdData = uni.getStorageSync("storeMdData");
      if (!mdData) {
        params["md_id"] = -1;
      }
      this.$allrequest.alipay.clearAllCartData(params).then((res) => {
        if (!res.code) {
          uni.showToast({
            title: "清除成功！",
            duration: 2000,
            icon: "none",
          });
          cb && cb();
        }
      });
    },
    // 关闭拼单
    stopSpellOrderMeal(flag_id, cb) {
      let params = {
        flag_id,
      };
      let mdData = uni.getStorageSync("storeMdData");
      if (!mdData) {
        params["md_id"] = -1;
      }
      this.$allrequest.alipay.closeSpellOrder(params).then((res) => {
        if (!res.code) {
          uni.removeStorageSync("flag_id");
          cb && cb();
        }
      });
    },
    // 更新门店数据
    updateMdData(id, cb) {
      if (id == -1) return;

      this.$allrequest.alipay.updateMdData({ md_id: id }).then((res) => {
        if (!res.code) {
          if (res.data) {
            let obj = {
              id: id,
              name: res.data.name,
              mobile: res.data.mobile,
              city_name: res.data.city_name,
              province_name: res.data.province_name,
              district_name: res.data.district_name,
              address: res.data.address,
              cover_url: res.data.cover_url,
              open_status: res.data.open_status,
              shop_time_type: res.data.shop_time_type,
              end_time: res.data.end_time,
              start_time: res.data.start_time,
              latitude: res.data.latitude,
              longitude: res.data.longitude,
              distance: "未知",
            };
            uni.setStorageSync("storeMdData", JSON.stringify(obj));
            this.storageMdId = id || "-1";
            cb && cb();
          }
        }
      });
    },
    // 创建一个flag_id
    createStoreFlagId() {
      let params = {};
      let mdData = uni.getStorageSync("storeMdData");
      if (!mdData) {
        params["md_id"] = -1;
      }
      this.$allrequest.alipay.createStoreFlagId(params).then((res) => {
        if (!res.code) {
          if (this.storeFlagId != res.data.flag_id && res.data.flag_id) {
            this.setFlagIdToStorage(res.data.flag_id);
            this.storeFlagId = res.data.flag_id;
          }
        }
      });
    },
    // 获取拼单状态  0: 正在进行中 1：已结束
    spellOrderStatus(flag_id, cb) {
      this.$allrequest.alipay.spellOrderStatus({ flag_id }).then((res) => {
        if (!res.code) {
          if (res.data.status == 1) {
            uni.removeStorageSync("flag_id");
            this.storeFlagId = "";
            uni.showToast({
              title: "拼单已结束！",
              duration: 2000,
              icon: "none",
            });
            clearInterval(this.intervalPoll);
          }
          cb && cb(res);
        }
      });
    },
    // 查询用户是否拼单选好了 1: 已选好 0：为选好
    checkUserSpellStatus(flag_id, cb) {
      this.$allrequest.alipay.checkUserSpellStatus({ flag_id }).then((res) => {
        if (!res.code) {
          cb && cb(res.data);
        }
      });
    },
  },
};
